package com.example.administrator.webviewtest;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.widget.Toast;

import com.example.administrator.webviewtest.domain.WebViewPayResult;
import com.example.administrator.webviewtest.utils.AppPayOrder;
import com.example.administrator.webviewtest.utils.FashJsonUtil;
import com.example.administrator.webviewtest.utils.PayUtils;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.github.lzyzsd.jsbridge.DefaultHandler;

public class MainActivity extends Activity {

    String HOST = "http://www.klg100.com.cn";
//    String HOST = "http://192.168.2.169:8080/shop";

    String webviewUrl = HOST + "/mobile";


    private WebSettings webSettings;
    private BridgeWebView myWebView;
    private long mExitTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myWebView = (BridgeWebView) findViewById(R.id.webview);
        webSettings = myWebView.getSettings();
        // 设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        //设置此属性，可任意比例缩放
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        //设置字符编码
        webSettings.setDefaultTextEncodingName("UTF-8");
        // 设置Web视图
       // myWebView.setWebChromeClient(new WebChromeClient());
        //获取手势焦点
        myWebView.requestFocusFromTouch();
        //设置代理
        String ua = myWebView.getSettings().getUserAgentString();
        myWebView.getSettings().setUserAgentString(ua + "\nklyb100");
        myWebView.setDefaultHandler(new DefaultHandler());
//        myWebView.addJavascriptInterface();
       /* myWebView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {// 载入进度改变而触发
                if (progress == 100) {
                    // mHandler.sendEmptyMessage(1);// 如果全部载入,隐藏进度对话框
                }
                super.onProgressChanged(view, progress);
            }
        });*/


        // 加载需要显示的网页
        myWebView.loadUrl(webviewUrl);
        System.out.println(webviewUrl);
        //点击后退按钮,让WebView后退一页(也可以覆写Activity的onKeyDown方法)
        myWebView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_BACK) {

                        if (myWebView.getUrl().equals(webviewUrl + "/") || myWebView.getUrl().equals(webviewUrl + "/brand") || myWebView.getUrl().equals(webviewUrl + "/cate") || myWebView.getUrl().equals(webviewUrl + "/cart") || myWebView.getUrl().equals(webviewUrl + "/cart/myinfo")) {
                            exit();
                            return true;    //已处理
                        } else if (myWebView.canGoBack()) {
                            myWebView.goBack();   //后退
                            return true;    //已处理
                        }
                    }
                }
                return false;
            }
        });

        //回调Java函数调用支付宝
        myWebView.registerHandler("toPay", new BridgeHandler() {

            private AppPayOrder order;

            @Override
            public void handler(String data, CallBackFunction function) {
                try {
                    //js返回值回来
                    order = FashJsonUtil.json2T(data, AppPayOrder.class);
                    order.setPayFee(0.01);//支付金额
                    final WebViewPayResult payResult = PayUtils.pay(MainActivity.this, order, function, myWebView);
                    System.out.println(payResult.getOrderNo());
                    System.out.println(payResult.isPay());
                    if (payResult.isPay()) {//支付成功
                        //function.onCallBack(payResult.getOrderNo());
                        //myWebView.loadUrl(HOST+"/app/v1/order/toback?payNo="+payResult.getOrderNo());
                        //js返回显示支付完成后的页面
                        myWebView.callHandler("payedResult", payResult.getOrderNo(), new CallBackFunction() {

                            @Override
                            public void onCallBack(String data) {
                                // TODO Auto-generated method stub
                                System.out.println(payResult.getOrderNo());
                            }

                        });
                    } else {//支付失败

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        });


        //js返回显示支付完成后的页面
       /* myWebView.callHandler("payedResult", "20165030714253655", new CallBackFunction() {

            @Override
            public void onCallBack(String data) {
                // TODO Auto-generated method stub
            }

        });*/

    }


    //返回鍵提示退出程序
    public void exit() {

        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();

        } else {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);

            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }

    @Override
    public void onBackPressed() {
        //super.onBackPressed();
        if (myWebView.canGoBack()) {
            myWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }
}
